package layui.controller.product;

import com.google.gson.Gson;
import layui.dao.ProductDao;
import layui.dao.impl.ProductDaoImpl;
import layui.entity.Product;
import layui.vo.PageVo;
import layui.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author lzp
 * @Date 2023-11-20
 */
@WebServlet("/admin/product/product_list_page")
public class FindByPageProductServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");


        // 当前页
        int page = Integer.parseInt(req.getParameter("page"));
        // 每页记录数
        int limit = Integer.parseInt(req.getParameter("limit"));

        String productName = req.getParameter("productName");
        String productType = req.getParameter("productType");

        Product p = new Product();

        p.setProductName(productName);
        p.setProductType(productType);

        ProductDao productDao = new ProductDaoImpl();

        List<Product> list = productDao.selectByPage(p,page,limit) ;
        Long count = productDao.selectByPageCount(p);

        /*
            把后台（服务器）的数据响应到前端页面，有以下两个方法：
            方法一（同步）：把数据设置在某个作用域对象 -> 页面跳转到 JSP 页面 -> JSTL + EL
            方法二（异步）：把数据封装到统一的响应对象 -> 把数据转换为 JSON 字符串 -> 通过 PrintWriter 对象，把 JSON 字符串输出到页面中 -> 把 JSON 字符串转换为 JavaScript 对象 -> DOM操作
         */
        PageVo responseData = new PageVo(200,"success",list,count);
        String json = new Gson().toJson(responseData);
        PrintWriter out = resp.getWriter();
        out.println(json);
        out.flush();
        out.close();
    }
}
